package org.myself.meeting.controller;


import org.myself.meeting.Utils.Constant;
import org.myself.meeting.model.*;
import org.myself.meeting.service.EmployeeService;
import org.myself.meeting.service.FileOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FileController {

    @Autowired
    FileOperationService fileOperationService;

    @Autowired
    EmployeeService employeeService;

    //展示文件上传到页面
    @RequestMapping("/filecloud")
    @ResponseBody
    public Result fileCloud(@RequestBody Base base){
        Map<String, List<FileOperation>> map = new HashMap<String, List<FileOperation>>();
        map.put("files",fileOperationService.getAllFiles());
        return new Result(200,"",map);
    }

    //云文件删除界面
    @RequestMapping("/filedelete")
    @ResponseBody
    public Result fileDelete(@RequestBody Base base){
        Map<String, List<FileOperation>> map = new HashMap<String, List<FileOperation>>();
        map.put("files",fileOperationService.getAllFiles());
        return new Result(200,"",map);
    }
    //云文件的删除
    @RequestMapping("/filedeletedo")
    @ResponseBody
    public Result fileDeleteDo(@RequestBody FileDeleteDo deleteDo){
        System.out.println(deleteDo.getId());
        Integer result = fileOperationService.deleteFileById(deleteDo.getId());

        if(result == 1){
            return new Result(200,"success操作成功",null);
        }else{
            return new Result(400,"error删除失败",null);
        }
    }


    //文件上传功能
    @RequestMapping(value="/fileupload",method= RequestMethod.POST)
    @ResponseBody
    public Result fileUpload(@RequestParam("username") String username,@RequestParam("file") MultipartFile file, HttpServletRequest request,  Model model) throws IOException {
        // 当前传来用户名
        System.out.println(username);

        //文件夹位置
        String rootPath = Constant.FILEPATH;

        // 原始名称
        String beforename = file.getOriginalFilename();
        System.out.println("原始名称："+beforename);

        //创建日期并且格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String datename = sdf.format(new Date());

        // 新文件名
        String newFileName = "my" + datename + beforename.substring(beforename.lastIndexOf("."));

        // 创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }

        // 拿到当前用户信息
        Employee emp = employeeService.getEmpsByUsername(username);

        //存放到数据库中
        FileOperation fileOperation = new FileOperation();
        fileOperation.setEmployeename(emp.getEmployeename());
        fileOperation.setEmployeeid(emp.getEmployeeid());
        fileOperation.setThetime(new Date());
        fileOperation.setFatherpath(newFile.getParentFile().toString());
        fileOperation.setFilename(newFileName);
        fileOperation.setFilerealname(beforename);

//        System.out.println(fileOperation.toString());

        Integer result = fileOperationService.addFiles(fileOperation);
        if (result == 1){
            // 将内存中的数据写入磁盘
            file.transferTo(newFile);
            Base base = new Base();
            base.setUsername(username);
            base.setRoles(emp.getRole().toString());
            return this.fileCloud(base);

        }else{
            return new Result(400,"上传失败",null);
        }

    }


    //文件下载功能
    @RequestMapping("/filedown")
    public void fileDown(@RequestBody FileDeleteDo deleteDo, HttpServletResponse response) throws Exception{
        System.out.println("id:"+deleteDo.getId());
        //获取服务器中的文件
        FileOperation fileOperation= fileOperationService.getFileById(deleteDo.getId());
        if (fileOperation == null){
            return;
        }
        String fileName = fileOperation.getFatherpath()+ File.separator +fileOperation.getFilename();
//        System.out.println("filename:"+fileName);
        File getfile = new File(fileName);

        if (!getfile.exists()){
            return ;
        }
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(getfile));

        //返回服务器中的文件
        String filename = fileOperation.getFilerealname();
        //转码，免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("application/octet-stream");
        response.setContentType(Files.probeContentType(Paths.get(fileName)));

        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
    }


}
